package cn.detu.ln.service.impl;

import cn.detu.ln.entity.Course;
import cn.detu.ln.mapper.CourseMapper;
import cn.detu.ln.service.CourseService;
import cn.detu.ln.utils.RestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Override
    public RestUtil selectAll() {
        return new RestUtil(200,"",courseMapper.selectList(null));
    }

    @Override
    public RestUtil selectCourse(Integer teaId) {
        Course course = courseMapper.selectOne(new QueryWrapper<Course>().eq("tea_id",teaId));
        if(course == null) return new RestUtil(500,"该教师没有带任何课程！",null);
        return new RestUtil(200,"查询成功！",course);
    }


    @Override
    public Course queryCourseById(Integer couId) {
        return courseMapper.selectOne(new QueryWrapper<Course>().eq("cou_id",couId));
    }

    @Override
    public RestUtil courseDelete(Integer couId) {
        return courseMapper.deleteById(couId)>0?new RestUtil(200,"删除成功",null):new RestUtil(500,"删除失败",null);
    }


    @Override
    public RestUtil courseUpdate(Course course) {
        return courseMapper.updateById(course)>0?new RestUtil(200,"修改成功",null):new RestUtil(500,"修改失败",null);
    }

    @Override
    public RestUtil courseInsert(Course course) {
        return courseMapper.insert(course)>0?new RestUtil(200,"添加成功",null):new RestUtil(500,"添加失败",null);
    }

    @Override
    public RestUtil queryCourseByPage(Integer current, Integer rows, String search) {
        // 1.根据查询条件判断构造的操作数据库的模糊查询条件
        // 如果search有值的话，就进行分页模糊查询，没有值的话就进行普通查询
        QueryWrapper<Course> queryWrapper = (search != null && search != "")?
                new QueryWrapper<Course>().like("cou_name",search) : null;
        // 2.根据mybatis-plus分页查询返回Page对象，MP规定，实现分页查询必须规定一个分页拦截器才会生效
        Page<Course> coursePage = courseMapper.selectPage(new Page<Course>(current,rows),queryWrapper);
        // 3.选择一个合适的数据结构封装返回的数据 Map数据结构
        HashMap<String, Object> map = new HashMap<>();
        // 4.使用Page对象获取分页显示的信息
        map.put("total",coursePage.getTotal());// 总条数
        map.put("pages",coursePage.getPages());// 总页数
        map.put("courses",coursePage.getRecords());// 当前页数据
        return coursePage != null ? new RestUtil(200,"",map) : null;
    }
}
